package com.amorcloud.pig.activity;

import android.app.Dialog;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amorcloud.pig.R;
import com.amorcloud.pig.adapter.CheckDataAdapter;
import com.amorcloud.pig.bean.CheckBean;
import com.amorcloud.pig.bean.GetDeviceNoResultBean;
import com.amorcloud.pig.bean.GetGroupNoResultBean;
import com.amorcloud.pig.bean.GetSellNoResultBean;
import com.amorcloud.pig.bean.StopCheckResultBean;
import com.amorcloud.pig.utils.CheckDaoUtil;
import com.amorcloud.pig.utils.DateUtil;
import com.amorcloud.pig.utils.HttpUtils;
import com.amorcloud.pig.utils.NetworkUtil;
import com.amorcloud.pig.utils.SharedPreferencesUtils;
import com.amorcloud.pig.utils.ToastUtil;
import com.amorcloud.pig.widget.UploadSuccessDialog;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class SellActivity extends BaseActivity implements View.OnClickListener {

    private Button btnStart, btnStop;
    private ImageView piciNoRefresh, deviceNoRefresh, sellNoRefresh;
    private Spinner spDeviceNo, spPiciNo, spSellNo;
    private EditText tvChePai;
    private TextView tvActualCount, tvTargetCount;
    private ListView listView;
    private String farmName;
    private List<String> deviceNoList = new ArrayList<>(), piciNoList = new ArrayList<>(), sellNoList = new ArrayList<>();
    private List<GetGroupNoResultBean.DataListBean> groupNoBeans; //所有批次号对象
    private Gson mGson = new Gson();
    private Animation rotationAnimation;
    private int time = 5;
    private Timer timer;
    private String groupNo = ""; //当前选中的批次号
    //当前批次号的盘点数量
    private String groupCount = "";
    private CheckDataAdapter checkDataAdapter;
    private List<String> checkDataList = new ArrayList<>();
    private int actualCount;

    @Override
    protected void init() {
        setContentView(R.layout.activity_sell);
        initCustomToolbar(this);
        initView();
        initData();
    }

    private void initView() {
        tvActualCount = findViewById(R.id.tv_actual_count);
        tvTargetCount = findViewById(R.id.tv_target_count);
        listView = findViewById(R.id.lv_check_data);
        listView.addHeaderView(LayoutInflater.from(this).inflate(R.layout.header_2_column, listView, false));
        deviceNoRefresh = findViewById(R.id.img_sell_device_refresh);
        deviceNoRefresh.setOnClickListener(this);
        piciNoRefresh = findViewById(R.id.img_sell_pici_refresh);
        piciNoRefresh.setOnClickListener(this);
        sellNoRefresh = findViewById(R.id.img_sell_no_refresh);
        sellNoRefresh.setOnClickListener(this);

        spDeviceNo = findViewById(R.id.sp_cell_device_no);
        spDeviceNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                final String selectValue = spDeviceNo.getSelectedItem().toString();
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        try {
                            String result = HttpUtils.checkDeviceStatus(selectValue);
                            JSONObject object = new JSONObject(result);
                            if (object.has("MsgCode")) {
                                if ("0".equals(object.get("MsgCode"))) {
                                    ToastUtil.showToastOnThread(SellActivity.this, "该设备没有使用。");
                                    mHandler.sendEmptyMessage(6); //恢复按钮状态。
                                    return;
                                } else if ("1".equals(object.get("MsgCode"))) {
                                    ToastUtil.showToastOnThread(SellActivity.this, "该设备正在使用。");
                                    mHandler.sendEmptyMessage(4); //设备使用中，只能停止盘点。
                                    return;
                                }
                            } else {
                                ToastUtil.showToastOnThread(SellActivity.this, "设备状态异常");
                                mHandler.sendEmptyMessage(6); //开始盘点报错，恢复按钮状态。
                                return;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spPiciNo = findViewById(R.id.sp_cell_pici_no);
        spSellNo = findViewById(R.id.sp_cell_no);
        spPiciNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                groupNo = spPiciNo.getSelectedItem().toString();
                if (groupNoBeans != null) {
                    groupCount = groupNoBeans.get(position).getCurNo();
                    Log.d("leihuiming", "groupCount = " + groupCount);
                    tvTargetCount.setText("任务盘点数量：" + groupCount);
                }
                mHandler.sendEmptyMessage(5);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        btnStart = findViewById(R.id.btn_sell_start);
        btnStart.setOnClickListener(this);
        btnStop = findViewById(R.id.btn_sell_stop);
        btnStop.setOnClickListener(this);
        btnStop.setEnabled(false);
        //车牌
        tvChePai = findViewById(R.id.etv_car_id);

        rotationAnimation = AnimationUtils.loadAnimation(this, R.anim.anim_rotate_refresh);
    }

    private void initData() {
        farmName = (String) SharedPreferencesUtils.getParam("farmName", "");
        timer = new Timer(true);
        deviceNoList.add("请选择设备...");
        updateDeviceNo();
        updatePiCiNo();
        checkDataAdapter = new CheckDataAdapter(this, checkDataList);
        listView.setAdapter(checkDataAdapter);
    }

    private void updateDeviceNo() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                String result = HttpUtils.getDeviceNo();
                Log.d("leihuiming", "get DeviceNo result = " + result);
                GetDeviceNoResultBean bean = mGson.fromJson(result, GetDeviceNoResultBean.class);
                if (bean != null) {
                    if ("0".equals(bean.getMsgCode())) {
                        if (bean.getCount() > 0) {
                            deviceNoList.addAll(bean.getRFIDList());
                            mHandler.sendEmptyMessage(0);
                        }
                    } else {
                        //Toast.makeText(SellActivity.this, "MsgCode: " + bean.getMsgCode() + " Msg: " + bean.getMsg(), Toast.LENGTH_SHORT).show();
                        ToastUtil.showToastOnThread(SellActivity.this, "MsgCode: " + bean.getMsgCode() + " Msg: " + bean.getMsg());
                    }
                }
            }
        }.start();
    }

    private void updatePiCiNo() {
        if (TextUtils.isEmpty(farmName)) {
            Toast.makeText(this, "未设置农场名", Toast.LENGTH_SHORT).show();
        } else {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    String result = HttpUtils.getGroupNo(farmName);
                    Log.d("leihuiming", "get GroupNo result = " + result);
                    GetGroupNoResultBean bean = mGson.fromJson(result, GetGroupNoResultBean.class);
                    if (bean != null) {
                        if ("0".equals(bean.getMsgCode())) {
                            if (bean.getCount() > 0) {
                                for (int i = 0; i < bean.getDataList().size(); i++) {
                                    piciNoList.add(bean.getDataList().get(i).getGroupNo());
                                }
                                groupNoBeans = bean.getDataList();
                                mHandler.sendEmptyMessage(1);
                            }
                        } else {
                            //Toast.makeText(SellActivity.this, "MsgCode: " + bean.getMsgCode() + " Msg: " + bean.getMsg(), Toast.LENGTH_SHORT).show();
                            ToastUtil.showToastOnThread(SellActivity.this, "MsgCode: " + bean.getMsgCode() + " Msg: " + bean.getMsg());
                        }
                    }
                }
            }.start();
        }
    }

    private void updateSellNo(final String groupNo) {
        if (!TextUtils.isEmpty(groupNo)) {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    String result = HttpUtils.getSellNo(groupNo);
                    Log.d("leihuiming", "updateSellNo result = " + result);
                    GetSellNoResultBean bean = mGson.fromJson(result, GetSellNoResultBean.class);
                    if (bean != null) {
                        if ("0".equals(bean.getMsgCode())) {
                            sellNoList.clear();
                            if (bean.getSellNo().size() > 0) {
                                sellNoList.addAll(bean.getSellNo());
                            } else {
                                ToastUtil.showToastOnThread(SellActivity.this, "该批次号没有对应销售单。");
                            }
                            mHandler.sendEmptyMessage(2);
                        } else {
                            //Toast.makeText(SellActivity.this, "MsgCode: " + bean.getMsgCode() + " Msg: " + bean.getMsg(), Toast.LENGTH_SHORT).show();
                            sellNoList.clear();
                            mHandler.sendEmptyMessage(2);
                            ToastUtil.showToastOnThread(SellActivity.this, "MsgCode: " + bean.getMsgCode() + " Msg: " + bean.getMsg());
                        }
                    }

                }
            }.start();
        }
    }

    private void doCheck(final CheckBean checkBean, final int startOrStop) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    String result = HttpUtils.pigCheck(checkBean, startOrStop);
                    Log.d("leihuiming", "do check result = " + result);
                    if (startOrStop == 1) { //开始盘点
                        startCheck(result);
                    } else { //停止盘点
                        stopCheck(result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void startCheck(String json) {
        try {
            JSONObject object = new JSONObject(json);
            if (object.has("MsgCode") && "0".equals(object.get("MsgCode"))) {
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        time--;
                        mHandler.sendEmptyMessage((time == 0 ? 4 : 3));
                    }
                }, 1000, 1000);
            } else {
                mHandler.sendEmptyMessage(6); //开始盘点报错，恢复按钮状态
                ToastUtil.showToastOnThread(SellActivity.this, "MsgCode: " + object.get("MsgCode") + " Msg: " + object.get("Msg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void stopCheck(String json) {
        try {
            StopCheckResultBean bean = mGson.fromJson(json, StopCheckResultBean.class);
            if ("0".equals(bean.getMsgCode())) {
                if (bean.getCount() > 0) {
                    checkBean.setCheckID(bean.getID());
                    checkDataList.clear();
                    checkDataList = bean.getData();
                    actualCount = bean.getCount();
                    Message message = Message.obtain();
                    if (groupCount.equals(bean.getCount())) {
                        message.what = 7; //显示盘点成功dialog
                        message.arg1 = bean.getCount();
                        checkBean.setCheckErMsg(bean.getMsg());
                        CheckDaoUtil.insert(checkBean);
                        checkBean = null;
                    } else {
                        message.what = 8; //显示盘点失败dialog
                        message.arg1 = bean.getCount() - Integer.parseInt(groupCount);
                    }
                    mHandler.sendMessage(message);
                } else {
                    ToastUtil.showToastOnThread(SellActivity.this, "盘点数量为0, 请重新盘点！");
                }
            } else {
                ToastUtil.showToastOnThread(SellActivity.this, "盘点失败, 请重新盘点！错误码：" + bean.getMsgCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    CheckBean checkBean;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_sell_device_refresh:
                deviceNoList.clear();
                deviceNoList.add("请选择设备...");
                deviceNoRefresh.startAnimation(rotationAnimation);
                updateDeviceNo();
                break;
            case R.id.img_sell_pici_refresh:
                piciNoList.clear();
                piciNoRefresh.startAnimation(rotationAnimation);
                updatePiCiNo();
                break;
            case R.id.img_sell_no_refresh:
                sellNoList.clear();
                sellNoRefresh.startAnimation(rotationAnimation);
                updateSellNo(spPiciNo.getSelectedItem().toString());
                break;
            case R.id.btn_sell_start:
                if(NetworkUtil.isNetworkConnected(this)) {
                    if (spDeviceNo.getSelectedItem() == null ||
                            spSellNo.getSelectedItem() == null ||
                            spPiciNo.getSelectedItem() == null ||
                            spDeviceNo.getSelectedItem().toString().startsWith("请") ||
                            TextUtils.isEmpty(tvChePai.getText().toString())) {
                        Toast.makeText(this, "请完整填写条件数据", Toast.LENGTH_SHORT).show();
                    } else {
                        timer = new Timer();
                        btnStop.setEnabled(false);
                        btnStart.setEnabled(false);
                        checkDataList.clear();
                        checkDataAdapter.setData(checkDataList);
                        createCheckBean();
                        doCheck(checkBean, 1);
                    }
                } else {
                    Toast.makeText(this, "网络错误，请设置网络。", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_sell_stop:
                if(NetworkUtil.isNetworkConnected(this)) {
                    if (spDeviceNo.getSelectedItem() == null ||
                            spSellNo.getSelectedItem() == null ||
                            spPiciNo.getSelectedItem() == null ||
                            spDeviceNo.getSelectedItem().toString().startsWith("请") ||
                            TextUtils.isEmpty(tvChePai.getText().toString())) {
                        Toast.makeText(this, "请完整填写条件数据", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    btnStart.setEnabled(true);
                    btnStop.setEnabled(false);
                    if (checkBean == null) {
                        createCheckBean();
                    }
                    doCheck(checkBean, 0);
                } else {
                    Toast.makeText(this, "网络错误，请设置网络。", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void createCheckBean() {
        checkBean = new CheckBean();
        checkBean.setRfidNumber(spDeviceNo.getSelectedItem().toString());
        checkBean.setOddNumber(spSellNo.getSelectedItem().toString());
        checkBean.setCheckType(4); //销售盘点
        checkBean.setDateTime(DateUtil.getYMDHMSStrDate(System.currentTimeMillis()));
        checkBean.setVecile(tvChePai.getText().toString()); //车牌号
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0://初始化设备号
                    if (deviceNoList.size() > 0) {
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(SellActivity.this, android.R.layout.simple_spinner_item, deviceNoList);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spDeviceNo.setAdapter(adapter);
                    }
                    break;
                case 1://初始化批次号
                    if (piciNoList.size() > 0) {
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(SellActivity.this, android.R.layout.simple_spinner_item, piciNoList);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spPiciNo.setAdapter(adapter);
                    }
                    break;
                case 2://初始化销售单号
                    if (sellNoList.size() > 0) {
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(SellActivity.this, android.R.layout.simple_spinner_item, sellNoList);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spSellNo.setAdapter(adapter);
                    } else {
                        spSellNo.setAdapter(null);
                    }
                    break;
                case 3: //停止盘点不可点击并显示倒计时
                    btnStop.setText("停止盘点(" + time + ")");
                    break;
                case 4://倒计时结束，按钮恢复可以点击状态
                    btnStop.setText("停止盘点");
                    btnStop.setEnabled(true);
                    btnStart.setEnabled(false);
                    timer.cancel();
                    timer = null;
                    time = 5;
                    break;
                case 5: //批次号更改的时候 更新销售单号
                    updateSellNo(groupNo);
                    break;
                case 6: //开始盘点报错, 初始化按钮状态
                    btnStart.setEnabled(true);
                    btnStop.setEnabled(false);
                    break;
                case 7://显示销售盘点成功dialog
                    Dialog dialog = UploadSuccessDialog.CreateSellSuccessDialog(SellActivity.this, msg.arg1);
                    dialog.show();
                    final WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
                    params.width = 650;
                    params.height = 550;
                    dialog.getWindow().setAttributes(params);
                    checkDataAdapter.setData(checkDataList);
                    tvActualCount.setText("实际盘点数量：" + actualCount);
                    break;
                case 8://显示销售盘点失败dialog
                    Dialog failDialog = CreateCheckFailDialog(msg.arg1);
                    failDialog.show();
                    final WindowManager.LayoutParams params1 = failDialog.getWindow().getAttributes();
                    params1.width = 800;
                    params1.height = 750;
                    failDialog.getWindow().setAttributes(params1);
                    checkDataAdapter.setData(checkDataList);
                    tvActualCount.setText("实际盘点数量：" + actualCount);
                    break;
                default:
                    break;
            }
        }
    };

    public Dialog CreateCheckFailDialog(int failCount) {
        final Dialog dialog = new Dialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_check_fail, null);
        final EditText errorMsg = view.findViewById(R.id.etv_check_fail_common);
        TextView msg1 = view.findViewById(R.id.sell_msg1);
        msg1.setText("当前猪只销售异常！");
        TextView message = view.findViewById(R.id.check_fail_count);
        final Button sureButton = view.findViewById(R.id.btn_sure);
        sureButton.setEnabled(false);
        errorMsg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.d("leihuiming", "beforeTextChanged s= " + s + " count=" + count);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.d("leihuiming", "onTextChanged s= " + s + " count=" + count);
                if (s.toString().length() >= 4) {
                    sureButton.setEnabled(true);
                } else {
                    sureButton.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.d("leihuiming", "afterTextChanged s= " + s.toString());
            }
        });

        sureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkBean.setCheckErMsg(errorMsg.getText().toString());
                CheckDaoUtil.insert(checkBean);
                checkBean = null;
                dialog.dismiss();
            }
        });
        if (failCount < 0) {
            message.setText(Html.fromHtml("猪只数量缺失<font color='#FF0000'>" + Math.abs(failCount) + "</font>只"));
        } else {
            message.setText(Html.fromHtml("猪只数量增多<font color='#FF0000'>" + failCount + "</font>只"));
        }
        dialog.setContentView(view);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        return dialog;
    }
}
